﻿package scrn;


import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;

import core.Man;
import core.Mess;
import core.Setting;
import mess.Message;


// ============================================================ Экран для съемки
public class Cam implements Runnable, Win {

// ================================================================== Переменные
// Камера
private Player player;
private VideoControl videoControl; /**/

public int picW = 160; // Ширина поля съемки, в точках
public int picH = 120;

public String shotSize = "&width=" + picW + "&height=" + picH; // Режим съемки

public boolean fFull = false; // Отображение во весь экран
public boolean fVisible = true; // Видимый/невидимый кадр


// Команды
private boolean[] coms = new boolean[ScrMan.COM_TOT];
{
	coms[ScrMan.COM_CAN] = true;
	coms[ScrMan.COM_SHOT] = true;
}

//Фон
private Image bg; // Картинка фона
private int scrBg1 = 0xb0d0ff; // Цвет фона экрана 1
private int scrBg2 = 0xffffff; // Цвет фона экрана 2

// Разное
public Win winOld; // Ссылка на предыдущее окно
//private boolean fRun = true;
private boolean fShot = false;
private int colText = 0x000000; // Цвет текста
private int colShad = 0xffffff; // Цвет тени

// =============================================================== Инициализация
public Cam() {

	Mess.m("Cam.init", "=====");

	init();
}


// ========================================================= Начальная настройка
public void init() {

	try {
		player = Manager.createPlayer("capture://video");
		player.prefetch();
		if ((videoControl = (VideoControl) player.getControl("VideoControl")) != null) {
			videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, Man.scrMan);
		}
	} catch (Exception pe) {
		Mess.err("Cam.init", pe);
	}

	makeBg();
	setPicW(picW);

}

public boolean chStat(String statText) {

	return false;
}

// ============================== Задать размер картинки с соблюдениеи пропорций
public void setPicW(int picW) {

	this.picW = picW;
	this.picH = picW * 3 / 4;

	try {
		videoControl.setDisplaySize(picW, picH);

		drawBg();

		videoControl.setDisplayLocation((Draw.dispW - picW) >> 1,
				(Draw.dispH - picH) >> 1);
	} catch (Exception e) {
		Mess.err("Cam.keyPressed", e);
	}

}

// =========================================== Освободить ресурсы и закрыть окно
public void close(int from) {

	try {
		videoControl.setVisible(false);
		player.stop();
		player.close();
		player = null;
		//		fRun = false;
	} catch (Exception e) {
		Mess.err("Cam.close", e);
	}
	if (from <= Mess.LOCAL) {
		Man.scrMan.retWin(winOld);
	}
}


// ============================================================== Отрисовать фон
public void drawBg() {

	synchronized (Man.main) {
		Draw.g.setClip(0, 0, Draw.dispW, Draw.dispH);
		Draw.g.drawImage(bg, 0, 0, Graphics.TOP | Graphics.LEFT);
	}
}

// ======================================================= Изменился статус сети
public void fOnline(boolean fOnline) {

	if (fOnline == false) {
		close(Mess.LOCAL);
	}
}


// ======================================================= Вернуть список команд
public boolean[] getComs() {

	return coms;
}


public boolean inText(int contType, int ContNum, Message message) {

	return false;
}


public boolean isGraphic() {

	return true;
}


public boolean keyPressed(int keyCode) {

	boolean fFlush = false;

	switch (keyCode) {
		case Canvas.UP:

			fFlush = true;
			break;

		case Canvas.DOWN:
			fFlush = true;
			break;

		case Canvas.LEFT:
			if (picW >= 10) {
				setPicW(picW >> 1);
				fFlush = true;
			}
			break;

		case Canvas.RIGHT:
			setPicW(picW << 1);
			fFlush = true;
			break;

		case Canvas.FIRE:
		case Canvas.GAME_A:
			shotSize = "";
			fFlush = shot();
			break;

		case Canvas.GAME_B:
			shotSize = "&width=" + picW + "&height=" + picH;
			fFlush = shot();
			break;

		case Canvas.GAME_C:
			shotSize = "&width=64&height=64";
			fFlush = shot();
			break;

		case Canvas.GAME_D:
			shotSize = "&width=160&height=120";
			fFlush = shot();
			break;
	}

	return fFlush;

}

public boolean keyState(int keyState) {

	return false;
}


// ============================================================= Отобразить окно
public void show(Win winOld) {

	if (winOld != null && winOld != this) {
		this.winOld = winOld;
	}

	if ((bg == null) || (bg.getWidth() != Draw.dispW)
			|| (bg.getHeight() != Draw.dispH)) { // Картинка фона еще не создана, или размер экрана изменился
		init();
	}

	drawBg();

	try {
		if (player.getState() != Player.STARTED) {
			player.start();
		}
		videoControl.setVisible(fVisible);
	} catch (Exception e) {
		Mess.err("Cam.keyPressed", e);
	}
}

// ====================================================================== Снимок
private boolean shot() {

	if (fVisible) {
		new Thread(this).start();
	} else {
		drawBg();
		fVisible = true;
		videoControl.setVisible(fVisible);
	}

	this.coms[ScrMan.COM_SHOT] = false;
	this.coms[ScrMan.COM_SEND] = true;
	Man.scrMan.setCom(coms);

	return true;
}

// ====================================================== Тик системного таймера
public boolean tick() {

	return false;
}


// =================================================== Создать всю картинку фона
private void makeBg() {

	try {
		if ((bg == null) || (bg.getWidth() != Draw.dispW)
				|| (bg.getHeight() != Draw.dispH)) { // Картинка фона еще не создана
			Mess.m("ScrSmile.makeBg", "Создаю картинки фона");

			bg = Image.createImage(Draw.dispW, Draw.dispH);

			Graphics g = bg.getGraphics();

			Draw.rectG(g, 0, 0, Draw.dispW, Draw.dispH >> 2, scrBg1, scrBg2);
			Draw.rectG(g, 0, Draw.dispH >> 2, Draw.dispW, Draw.dispH
					- (Draw.dispH >> 2), scrBg2, scrBg1);
		}

	} catch (Exception e) {
		Mess.err("ScrSmile.makeBg", "Не могу создать картинку фона", e);
	}
}

// ========================================================= Формирование снимка
public void run() {

	byte[] byteImage;
	Image image;

	try {
		byteImage = videoControl.getSnapshot(Setting.camImgEnc + shotSize);
		Mess.m("Cam.run", "Размер снимка " + byteImage.length + " Б");
		image = Image.createImage(byteImage, 0, byteImage.length);
	} catch (MediaException e) {
		Mess.err("Cam.tick", e);
		image = null;
		byteImage = null;
	}

	if (image != null && byteImage != null) {
		Draw.g.drawImage(image, Draw.dispW >> 1, Draw.dispH >> 1, Graphics.HCENTER
				| Graphics.VCENTER);
		Draw.drawShadText("" + image.getWidth() + "x" + image.getHeight(),
				Draw.fontStat, Draw.fact2, Draw.fact2, colText, colShad);
		Draw.drawShadText("" + byteImage.length + " Б", Draw.fontStat, Draw.fact2,
				Draw.fact2 + Draw.fontStatH, colText, colShad);
	}

	fShot = false;
	fVisible = false;
	videoControl.setVisible(fVisible);

}


// ============================================================ Обработка команд
public void command(Command command) {

	if (command == Man.scrMan.coms[ScrMan.COM_CAN]) {
		close(Mess.LOCAL);
	} else if (command == Man.scrMan.coms[ScrMan.COM_SHOT]) {
		shot();
	} else if (command == Man.scrMan.coms[ScrMan.COM_SEND]) {
		shot();
	}
}

}
